package com.nowoe.server;

import com.nowoe.server.http.Request;
import com.nowoe.server.http.Response;
import com.nowoe.server.servlet.HttpServlet;
import com.nowoe.server.util.XmlParser;

import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 倚栏听风 2024/1/5 14:44
 */

public class Bootstrap {
    private int port = 8080;
    private Map<String, HttpServlet> servletMap = new HashMap<>();

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    private void init() {
        URL resource = this.getClass().getClassLoader().getResource("web.xml");
        if (resource == null) {
            throw new RuntimeException("web.xml not found");
        }
        XmlParser.parseXml(resource, servletMap);
    }


    public void start() {
        try {
            ServerSocket serverSocket = new ServerSocket(port);
            System.out.println("Server started at " + port);
            init();
            while (true) {
                Socket socket = serverSocket.accept();
                InputStream inputStream = socket.getInputStream();
                Request request = new Request(inputStream);
                Response response = new Response(socket.getOutputStream());
                if (servletMap.get(request.getUri()) == null) {
                    response.outputHtml(request.getUri());
                } else {
                    HttpServlet httpServlet = servletMap.get(request.getUri());
                    httpServlet.service(request, response);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    public static void main(String[] args) {
        Bootstrap bootStrap = new Bootstrap();
        bootStrap.start();
    }
}
